package com.pzl.hwr;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.pzl.hwr.adapter.WordsAdapter;
import com.pzl.hwr.util.HciCloudHwrHelper;
import com.pzl.hwr.util.HciCloudSysHelper;
import com.pzl.hwr.util.IHwrListener;
import com.pzl.hwr.util.Util;
import com.sinovoice.hcicloudsdk.common.HciErrorCode;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.Arrays;


public class HWR1Activity extends AppCompatActivity implements SurfaceHolder.Callback, WordsAdapter.Listener, IHwrListener {

    private static final String TAG = "HWR1Activity";

    private EditText et;

    /**
     * 加载用户信息工具类
     */
    private HciCloudSetting mHciCloudSetting;

    private static final int MAX_POINT = 2048;

    private static final int RECOG_RESULT = 10000;

    private static final int RECOG_ERROR = 10001;

    private SurfaceHolder surfaceHolder;

    private SurfaceView surface;

    private Paint paint;

    private Path path;

    private int top;

    private int bottom;

    private boolean isRunning = true;

    private Canvas canvas;

    private boolean start = true;

    private long init;

    private long now;

    private int mCurIndex;

    private short[] mPoints = null;

    private int mCurX, mCurY;

    private boolean mEnd;

    private RecyclerView rv;

    //---------------

    HciCloudSysHelper hciCloudSysHelper;

    HciCloudHwrHelper hciCloudHwrHelper;

    HeaderAndFooterWrapper mHeaderAndFooterWrapper;

    WordsAdapter wordsAdapter;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hwr1);
        initView();

        int errCode = initHciCloud();
        Log.d(TAG, "HciCloudHwr.hciHwrInit ->  errorCode=" + errCode);
        if (errCode != HciErrorCode.HCI_ERR_NONE) {
            Toast.makeText(this, "初始化失败，错误码是" + errCode, Toast.LENGTH_SHORT).show();
        }

    }

    private void initView() {
        et = (EditText) findViewById(R.id.et);

        rv = (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new GridLayoutManager(this, 6));
        //rv.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL|DividerItemDecoration.VERTICAL));
        rv.setVisibility(View.GONE);
        initAdapter();

        surface = (SurfaceView) findViewById(R.id.surface);
        surfaceHolder = surface.getHolder();        //获得SurfaceHolder对象
        surface.setZOrderOnTop(true);               //使surface可见
        surfaceHolder.setFormat(PixelFormat.TRANSPARENT);  //设置背景透明
        surfaceHolder.addCallback(this);          //为SurfaceView添加状态监听

        paint = new Paint();          //创建一个画笔对象
        path = new Path();

        mPoints = new short[MAX_POINT * 2];
        mCurIndex = 0;
    }

    private void initAdapter() {
        wordsAdapter = new WordsAdapter(null, HWR1Activity.this, HWR1Activity.this, Util.unit(HWR1Activity.this, 6));
        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(wordsAdapter);

        LinearLayout ll = new LinearLayout(this);
        ll.setGravity(Gravity.CENTER);
        ll.setPadding(0, 15, 0, 15);
        ImageView iv = new ImageView(this);
        iv.setMaxHeight(260);
        iv.setMaxWidth(260);
        iv.setImageResource(R.drawable.close);
        ll.addView(iv);
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rv.setVisibility(View.GONE);
            }
        });
        mHeaderAndFooterWrapper.addFootView(ll);
        rv.setAdapter(mHeaderAndFooterWrapper);
    }

    /**
     * 把坐标添加到short数组
     *
     * @param x
     * @param y
     * @return
     */
    private boolean addStroke(short x, short y) {
        if (mCurX >= 0 && mCurY >= 0) {
            if ((mCurIndex / 2) < (MAX_POINT - 2)) {
                mPoints[mCurIndex] = x;
                mCurIndex++;
                mPoints[mCurIndex] = y;
                mCurIndex++;
                return true;
            } else if ((mCurIndex / 2) == (MAX_POINT - 2)) {
                mPoints[mCurIndex] = -1;
                mCurIndex++;
                mPoints[mCurIndex] = 0;
                mCurIndex++;
                return true;
            }
        }
        return false;
    }

    /**
     * 最后一笔添加坐标(-1,-1)
     */
    public void addLastStrokePoint() {
        if (mCurIndex < 2 || (mPoints[mCurIndex - 1] == -1 && mPoints[mCurIndex - 2] == -1)) {
            return;
        }
        mPoints[mCurIndex] = -1;
        mCurIndex++;
        mPoints[mCurIndex] = -1;
        mCurIndex++;
    }

    /**
     * 每次抬笔添加坐标(-1,0)
     */
    private void addStrokeEnd() {
        mPoints[mCurIndex] = -1;
        mCurIndex++;
        mPoints[mCurIndex] = 0;
        mCurIndex++;
    }

    /**
     * 重置笔迹点数据
     */
    private void resetStroke() {
        mPoints = new short[MAX_POINT * 2];
        mCurIndex = 0;
    }

    /**
     * 获取笔迹点数组
     *
     * @return 笔迹点数组
     */
    public short[] getStroke() {
        mEnd = true;
        addStrokeEnd();
        addLastStrokePoint();
        short[] stroke = new short[mCurIndex];
        System.arraycopy(mPoints, 0, stroke, 0, mCurIndex);

        return stroke;
    }


    /**
     * 灵云初始化
     *
     * @return 0成功，其他失败
     */
    private int initHciCloud() {

        boolean loadResult = HciCloudSetting.getInstance().loadSetting(this);

        hciCloudSysHelper = HciCloudSysHelper.getInstance();
        hciCloudHwrHelper = HciCloudHwrHelper.getInstance();
        int errorCode = hciCloudSysHelper.init(this);
        if (errorCode != HciErrorCode.HCI_ERR_NONE) {
            return errorCode;
        }
        ArrayList<String> initCapKeys = new ArrayList<>();
        initCapKeys.add("hwr.local.freestylus");
        initCapKeys.add("hwr.local.associateword");
        errorCode = hciCloudHwrHelper.initHwr(this, initCapKeys);//初始化本地手写和联想
        if (errorCode != HciErrorCode.HCI_ERR_NONE) {
            return errorCode;
        }
        return HciErrorCode.HCI_ERR_NONE;
    }


    /**
     * 灵云系统反初始化
     */
    private void releaseHciCloud() {
        if (hciCloudHwrHelper != null) {
            hciCloudHwrHelper.releaseHwr();
        }
        if (hciCloudSysHelper != null) {
            // 释放HciCloudSys，当其他能力全部释放完毕后，才能调用HciCloudSys的释放方法
            hciCloudSysHelper.release();
        }
    }


    /**
     * 清空Canvas上的笔迹
     */
    private void clearCanvas() {
        for (int i = 0; i < 4; i++) {
            try {
                if (surfaceHolder != null) {
                    canvas = surfaceHolder.lockCanvas();
                    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                    path.reset();
                    resetStroke();
                    mEnd = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }
            }
        }
    }

    /**
     * 再Canvas上画
     */
    private void drawView() {
        try {
            if (surfaceHolder != null) {
                canvas = surfaceHolder.lockCanvas();
                canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
                paint.setColor(Color.BLACK);
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(5);

                canvas.drawPath(path, paint);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (canvas != null) {
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
    }

    Runnable wlineThread = new Runnable() {

        @Override
        public void run() {
            while (isRunning) {
                drawView();
                if (start) {
                    long temp = System.currentTimeMillis() - now;
//                    Log.d(TAG, "temp=" + temp);
                    if (temp > 1000 && temp < 100000) {      //抬笔时间超过1秒，加上坐标(-1,-1),过滤第一次时间的计算
                        short[] data = getStroke();
                        hciCloudHwrHelper.recog(data, "hwr.local.freestylus", HWR1Activity.this);

                        start = false;
                        clearCanvas();
                    }
                }
            }
        }
    };

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        int[] location = new int[2];
        surface.getLocationOnScreen(location);
        top = location[1];
        Log.d(TAG, "top = " + top);
        bottom = top + surface.getHeight();
        Log.d(TAG, "bottom = " + bottom);
        //开启一个绘画线程
        new Thread(wlineThread).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isRunning = false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getY() >= top && event.getY() <= bottom) {
            start = true;
            init = now;
            now = System.currentTimeMillis();
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (now - init >= 100 && now - init <= 1000) {      //抬笔操作，加上(-1,0)
                        addStrokeEnd();
                    }
                    path.moveTo(event.getX(), event.getY() - top);
                    break;

                case MotionEvent.ACTION_MOVE:
                    path.lineTo(event.getX(), event.getY() - top);
                    addStroke((short) event.getX(), (short) event.getY());
                    break;

                default:
                    break;
            }
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isRunning = false;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        releaseHciCloud();
        super.onDestroy();
    }

    @Override
    public void onWordClick(String word) {
        //Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
        rv.setVisibility(View.GONE);
        et.append(word);
        hciCloudHwrHelper.associateWord(word, "hwr.local.associateword", HWR1Activity.this);
    }


    @Override
    public void onHwrResult(final ArrayList<String> result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (result == null || result.isEmpty()) return;
                et.append(result.get(0));
                hciCloudHwrHelper.associateWord(result.get(0), "hwr.local.associateword", HWR1Activity.this);

            }
        });
    }

    @Override
    public void onAssociateResult(ArrayList<String> result) {
        Log.d(TAG, "联想结果：" + Arrays.toString(result.toArray()));
        rv.setVisibility(View.VISIBLE);
        wordsAdapter.setData(result);
        mHeaderAndFooterWrapper.notifyDataSetChanged();
    }


}
